package struts.util;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import struts.form.XmlBean;

public class StrutsConfigReader {
    public StrutsConfigReader(){
        
    }
    
    public static Map<String,XmlBean> getStrutsActionBeanMap(String xmlPath) throws Exception {
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(new File(xmlPath));
        Element root = document.getRootElement();

        Element actionroot = root.getChild("action-mapping");
        List<Element> action = actionroot.getChildren();
        Map<String,XmlBean> actionMap = new HashMap<String, XmlBean>();
        for(Element e : action) {
            XmlBean actionBean = new XmlBean();
            String name = e.getAttributeValue("name");
            actionBean.setBeanName(name);
            
            //装载formClass
            Element actionForm = root.getChild("formbeans");
            List<Element> form = actionForm.getChildren();
            for(Element fb : form) {
                if(name.equals(fb.getAttributeValue("name"))){
                    String formclass = fb.getAttributeValue("class");
                    actionBean.setFormClass(formclass);
                    break;
                }
            }
            
            String path = e.getAttributeValue("path");
            actionBean.setPath(path);
            
            String type = e.getAttributeValue("type");
            actionBean.setActionType(type);
            
            List<Element> forward = e.getChildren();
            Map<String,String> forwardMap = new HashMap<String, String>();
            for(Element x: forward) {
                String fname = x.getAttributeValue("name");
                String fvalue = x.getAttributeValue("value");
                forwardMap.put(fname, fvalue);
            }
            actionBean.setActionForward(forwardMap);
            actionMap.put(path, actionBean);
        }
        return actionMap;
    }
    
    public static void main(String[] args) throws Exception {
        Map<String,XmlBean> actionMap = getStrutsActionBeanMap("");
        Set<String> set = actionMap.keySet();
        for(Iterator it=set.iterator();it.hasNext();){
            String key = (String)it.next();
            System.out.println(key);
            System.out.println(actionMap.get(key));
        }
    }
}
